<%@ page import="java.util.Date" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="java.util.Random" %>
<%@ page import="util.DBUtil" %>
<%@ page import="java.sql.ResultSet" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<%
    /*根据购物车内容生成订单*/
    //1.生成订单编号 yyyyymmdd+6位随机数
    //1.1获得当前时间yyyy-mm-dd
    Date date=new Date();
    SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
    String  sday=sdf.format(date);
    //1.2产生6位随机数
    Random rd=new Random();
    int no=100000+rd.nextInt(900000);
    String order_no=sday+no;//设置订单编号
    //2.计算总金额
    DBUtil dbUtil=new DBUtil();
    String sql="select sum(sale_money) as total_money "
            +" from tb_cart "
            +" where member_id=0 ";
    ResultSet rs=dbUtil.query(sql);
    rs.next();
    String total_money=rs.getString("total_money");
    //3.生成一条订单记录
    sql="insert into tb_order(member_id,order_no,total_money,order_date,status)"
            +"values(0,'"+order_no+"','"+total_money+"',now(),0)";
    int n=dbUtil.update(sql);
    //获得新加入订单记录的id
    sql="select max(id) as id from tb_order";
    rs=dbUtil.query(sql);
    rs.next();
    int new_order_id=rs.getInt("id");
    //4.生成订单内容tb_order_item里面的数据--购物车内容对于
    sql="select * from tb_cart"
            +" where member_id= 0 ";
    rs=dbUtil.query(sql);
    while (rs.next()){
        sql="insert into tb_order_item(" +
                "order_id,product_id,sale_num,sale_price,sale_money)"
                +"values('"+new_order_id+"','"+rs.getString("product_id")+"','" +
                rs.getString("sale_num")+"','"+rs.getString("sale_price")+"','"+rs.getString("sale_money")+"')";
        dbUtil.update(sql);
    }
    //5.清空购物车
    sql="delete from tb_cart where member_id = 0";
    dbUtil.update(sql);
    //跳转到内容展示页面
    response.sendRedirect("order_info.jsp?id="+new_order_id);
%>